package com.woniu.gateway.configuration;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.http.converter.HttpMessageConverter;

import java.net.UnknownHostException;
import java.util.stream.Collectors;

/**
 * @ClassName HttpMessageConvertersConfiguration
 * @Description 信息转换器 redis序列化器
 * @Author shanshan
 * @Date 2022/10/25 11:52
 * @Version 1.0
 **/
@Configuration
public class HttpMessageConvertersConfiguration {

    //配置redis序列化器
    //缺点:存储格式，有类型，占内存空间
//    @Bean
    public RedisTemplate<String, Object>  redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<String, Object>  template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //修改默认序列化器
        //template.setDefaultSerializer(RedisSerializer.json());
        //分别设置k和V的序列化格式 K--String   V--JSON
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }
}